package com.tsfyun.scm.service.third;

import com.tsfyun.common.base.enums.shortmsg.ShortMessagePlatformEnum;
import com.tsfyun.scm.dto.support.SendSmsDTO;
import com.tsfyun.scm.entity.third.LogSms;
import com.tsfyun.scm.stream.send.ScmProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description:
 * @CreateDate: Created in 2021/9/15 15:58
 */
@RefreshScope
@Slf4j
public abstract class AbstractMessageService {

    @Value("${sms.isSend:false}")
    public Boolean isSend;

    @Autowired
    private ILogSmsService logSmsService;

    @Autowired
    private ScmProcessor scmProcessor;

    /**
     * 对接具体大短信平台SDK发送短信
     * @param templateCode
     * @param phoneNo
     * @param templateParam
     * @return
     */
    public abstract String send(String templateCode,String phoneNo,String templateParam);

    @Transactional(rollbackFor = Exception.class)
    public void sendNoticeMessageWithMQ(ShortMessagePlatformEnum shortMessagePlatformEnum,LogSms logSms, String templateCode, String paramJson) {
        if(isSend) {
            SendSmsDTO dto = new SendSmsDTO();
            dto.setMsgPlatform(shortMessagePlatformEnum.getCode());
            dto.setId(logSms.getId());
            dto.setPhoneNo(logSms.getPhoneNo());
            dto.setTemplateCode(templateCode);
            dto.setParamJson(paramJson);
            scmProcessor.sendSms(dto);
        } else {
            log.warn("短信开关未开启，暂不发送短信");
            logSms.setBackMessage("云短信发送未开启");
            logSmsService.updateById(logSms);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void consumeNoticeMessageWithMQ(SendSmsDTO dto) {
        LogSms logSms = logSmsService.getById(dto.getId());
        if(Objects.nonNull(logSms)) {
            String message = send(dto.getTemplateCode(),dto.getPhoneNo(),logSms.getContent());
            logSms.setBackMessage(message);
            logSmsService.updateById(logSms);
        }
    }


}
